package ajaxjs.service;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import ajaxjs.config.Application;
import ajaxjs.net.Request;

public abstract class Service_Restful extends Service {
	/**
	 * 获取单个对象，JSON 结构如 {"foo":bar};
	 * @param url
	 * @param params
	 * @return
	 */
	public Map<String, Object> getInfo(String url, Map<String, String> params){
		String id = params.get("id").toString();
		params.remove("id");
		
		String fullUrl = getServiceUrl(url + id, params); // 注入！
		String jsCode = get(fullUrl);
//		System.out.println("jsCode:"+jsCode);
		
		return Application.jsRuntime.NativeObject2Hash(jsCode);
	}	
	
	/**
	 * 没有 id 参数时就获取最新的那条记录
	 * @param request
	 * @param entry
	 * @return
	 */
	public Map<String, Object> getLastInfo(HttpServletRequest request, String entry, String where){
		Map<String, Object> feedback = null;
		if(request.getParameter("id") != null){
			feedback = getInfo("/" + entry + "/", Request.getId(request));
		}else{
			int MaxId = where != null ? ajaxjs.admin.entry.CRUD.getMaxId(entry, where) 
									  : ajaxjs.admin.entry.CRUD.getMaxId(entry);
			feedback = getInfo("/" + entry + "/", MaxId);
		}
		request.setAttribute(entry, feedback);
		return feedback;
	}
	public Map<String, Object> getLastInfo(HttpServletRequest request, String entry){
		return getLastInfo(request, entry, null);
	}
//	/**
//	 * 访问接口 （最原始的版本）
//	 * @param entity
//	 * @return
//	 */
//	public static Map<String, Object> getEntityById(String entity){
//		HttpServletRequest request = Request;
//		 
//		String  id = request.getParameter("id"), root = (String)App.config.get("root"),
//				url = "http://" + request.getServerName() + ":" + request.getServerPort() + root + "/service/" +  entity + "/" + id;
//		
//		com.ajaxjs.bigfoot.net.Net.request = request;
//		
//		String JSON_Str = new com.ajaxjs.bigfoot.net.Net().get(url);
//		
//		java.util.Map<String, Object> data = JS_ScriptEngine.NativeObject2Hash(JSON_Str);
//		request.setAttribute("data", data);
//		
//		return data;
//	}
	
}
